package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.qo.RoleQuery;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.JsonResult;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleServiceImpl;
    @Autowired
    private IPermissionService permissionServiceImpl;

    @RequestMapping("/list")
    @RequiresPermissions(value = {"role:list", "角色列表"}, logical = Logical.OR)
    public String list(Model model, @ModelAttribute("qo") RoleQuery qo) {
        PageInfo<Role> result = roleServiceImpl.query(qo);
        model.addAttribute("result", result);
        return "/role/list";
    }

    @RequestMapping("/input")
    @RequiresPermissions(value = {"role:input", "角色新增编辑页面跳转"}, logical = Logical.OR)
    public String input(Model model, Long id) {
        if (id != null) {
            Role role = roleServiceImpl.get(id);
            model.addAttribute("role", role);
        }
        List<Permission> permissions = permissionServiceImpl.listAll();
        model.addAttribute("permissions", permissions);
        return "/role/input";
    }

    @RequestMapping("/delete")
    @RequiresPermissions(value = {"role:delete", "角色删除"}, logical = Logical.OR)
    @ResponseBody
    public JsonResult delete(Long id) {
        roleServiceImpl.delete(id);
        return new JsonResult("删除成功", true);
    }

    @RequestMapping("/saveOrUpdate")
    @RequiresPermissions(value = {"role:saveOrUpdate", "角色新增编辑"}, logical = Logical.OR)
    @ResponseBody
    public JsonResult saveOrUpdate(Role role, Long[] ids) {
        if (role.getId() != null) {
            roleServiceImpl.update(role, ids);
        } else {
            roleServiceImpl.save(role, ids);
        }
        return new JsonResult("新增或修改成功", true);
    }

}
